package com.ml.mall.service.supplier.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.bean.base.ApiRestResult;
import com.ml.mall.bean.page.Page;
import com.ml.mall.bean.req.BaseBeanReq;
import com.ml.mall.bean.req.order.OrderEditReq;
import com.ml.mall.bean.req.supplier.OrderMQueryPageReq;
import com.ml.mall.bean.res.order.OrderMQueryPageRes;
import com.ml.mall.bean.res.order.vo.OrderChangeArrVO;
import com.ml.mall.bean.res.supplier.SupplierOrderQueryOneRes;
import com.ml.mall.bean.res.supplier.vo.OrderDataVO;
import com.ml.mall.bean.vo.OrderDetailArrVO;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.company.SysCompanyLogisticsInfo;
import com.ml.mall.entity.coupon.SysCoupon;
import com.ml.mall.entity.coupon.SysCouponRecord;
import com.ml.mall.entity.delivery.SysOrderDelivery;
import com.ml.mall.entity.detail.SysOrderDetail;
import com.ml.mall.entity.msg.SysOrderMsg;
import com.ml.mall.entity.order.SysOrder;
import com.ml.mall.entity.state.SysOrderState;
import com.ml.mall.entity.supplier.SysOrderSupplier;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.enums.RetStatusNum;
import com.ml.mall.mapper.coupon.SysCouponMapper;
import com.ml.mall.mapper.coupon.SysCouponRecordMapper;
import com.ml.mall.mapper.delivery.SysOrderDeliveryMapper;
import com.ml.mall.mapper.detail.SysOrderDetailMapper;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.mapper.state.SysOrderStateMapper;
import com.ml.mall.mapper.supplier.SysOrderSupplierMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.asyn.OrderMailServiceImplAsyn;
import com.ml.mall.service.company.SysCompanyLogisticsInfoService;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.delivery.SysOrderDeliveryService;
import com.ml.mall.service.detail.SysOrderDetailService;
import com.ml.mall.service.msg.SysOrderMsgService;
import com.ml.mall.service.order.SysOrderService;
import com.ml.mall.service.state.SysOrderStateService;
import com.ml.mall.service.supplier.SysOrderSupplierService;
import com.ml.mall.service.tax.TaxService;
import com.ml.mall.service.variant.SysProductVariantSkuService;
import com.ml.mall.utils.NumberUtils;
import com.ml.mall.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysOrderSupplierServiceImpl extends ServiceImpl<SysOrderSupplierMapper, SysOrderSupplier> implements SysOrderSupplierService{

    @Autowired
    private SysOrderSupplierMapper sysOrderSupplierMapper;
    @Autowired
    @Lazy
    private SysOrderDeliveryService sysOrderDeliveryService;
    @Autowired
    private SysOrderDeliveryMapper sysOrderDeliveryMapper;
    @Autowired
    @Lazy
    private SysOrderService sysOrderService;
    @Autowired
    private SysOrderStateMapper sysOrderStateMapper;
    @Autowired
    private SysOrderDetailMapper sysOrderDetailMapper;
    @Autowired
    private OrderMailServiceImplAsyn orderMailServiceImplAsyn;
    @Autowired
    private SysCouponMapper sysCouponMapper;
    @Autowired
    private TaxService taxService;
    @Autowired
    private SysOrderMsgService sysOrderMsgService;
    @Autowired
    private SysOrderDetailService sysOrderDetailService;
    @Autowired
    private SysCompanyService sysCompanyService;
    @Autowired
    private SysOrderStateService sysOrderStateService;
    @Autowired
    private SysProductVariantSkuService sysProductVariantSkuService;
    @Autowired
    private SysCompanyLogisticsInfoService sysCompanyLogisticsInfoService;
    @Autowired
    private SysCouponRecordMapper sysCouponRecordMapper;
    @Autowired
    private SysOrderMapper sysOrderMapper;
    @Override
    public List<SysOrderSupplier> selectSupplierOidBySupOid(Long oid) {
        return sysOrderSupplierMapper.selectSordByOid(oid);
    }

    @Override
    public SysOrderSupplier selectSysOrderSupplierBySupOid(String supplierOid) {
        QueryWrapper<SysOrderSupplier> w1 = new QueryWrapper<>();
        w1.eq("supplier_oid",supplierOid);
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectOne(w1);
        return sysOrderSupplier;
    }

    @Override
    public Page<OrderMQueryPageRes> sysOrderMQueryPage(OrderMQueryPageReq req) {
        log.info("req===={}",req);
        SysUser sysUser=JwtUtil.getCurrentUser();
        IPage<SysOrderSupplier> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(req.getPageIndex(),req.getPageNum());
        QueryWrapper<SysOrderSupplier> w1 = new QueryWrapper<>();
        if(StringUtils.isNotBlank(req.getOid())){
            w1.eq("supplier_oid",req.getOid()); //查询卖家单号
        }
        if(req.getState()!=null){
            w1.eq("state",req.getState());
        }
        if(req.getDateTime() != null){
            w1.eq("date(create_at)",req.getDateTime());
        }
        if(StringUtils.isNotBlank(req.getSubblierCompanyName())){
            w1.like("supplier_company_name",req.getSubblierCompanyName());
        }
        if(!sysUser.getRoleType().equals(CommonConsts.ROLE_TYPE_ADMIN)){
            w1.eq("supplier_id",sysUser.getCompanyId());
        }
        w1.gt("state",0);

        w1.orderByDesc("id");

        IPage<SysOrderSupplier> page = sysOrderSupplierMapper.selectPage(iPage, w1);

        Page<OrderMQueryPageRes> result = new Page<>(req.getPageIndex(),req.getPageNum());
        if(page!=null){
            result.setTotal((int)page.getTotal());
            List<SysOrderSupplier> records = page.getRecords();
            if(records!=null&&records.size()>0){
                List<OrderMQueryPageRes> list = new ArrayList<>();
                for(SysOrderSupplier s:records){
                    OrderMQueryPageRes orderMQueryPageRes = new OrderMQueryPageRes();
                    BeanUtils.copyProperties(s,orderMQueryPageRes);
                    //查询订购公司
                    SysOrder sysOrder = sysOrderService.selectOrderByOid(s.getOid());
                    if(sysOrder!=null){
                        orderMQueryPageRes.setPurchaseCompanyName(sysOrder.getCompanyName());
                    }
                    orderMQueryPageRes.setSubblierCompanyName(s.getSupplierCompanyName());
                    //查询接收日期
                    SysOrderDelivery sysOrderDelivery = sysOrderDeliveryService.selectSysOrderDeliveryByOid(s.getSupplierOid());
                    if(sysOrderDelivery!=null){
                        orderMQueryPageRes.setDeliveryAt(sysOrderDelivery.getCreateAt());
                    }
                    list.add(orderMQueryPageRes);
                }
                result.setRecords(list);
            }
        }
        return result;
    }

    @Override
    @Transactional
    public int sysOrderSupplierEdit(OrderEditReq orderEditReq) {
        SysUser sysUser = JwtUtil.getCurrentUser();
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(orderEditReq.getId());
//      检验状态是否正向修改；且每次大于步长为1
        Integer changeState = Integer.valueOf(orderEditReq.getState());
        if(changeState - sysOrderSupplier.getState() > 1 || changeState - sysOrderSupplier.getState() <= 0 ){
            log.info("orderEditReq==state===err={}",orderEditReq);
            if(!changeState.equals(7)){ //步长大于1；可以直接拒绝
                return 0;
            }
        }
        SysOrderSupplier entity = new SysOrderSupplier();
        entity.setId(orderEditReq.getId());
        entity.setState(Integer.parseInt(orderEditReq.getState()));
        int b = sysOrderSupplierMapper.updateById(entity);
        //创建记录;检测是否完成
        sysOrderStateService.createOrderState(sysOrderSupplier.getSupplierOid(),Integer.valueOf(orderEditReq.getState()),sysOrderSupplier.getOid());
        //支持关联物流信息;配货或者已完成
        if(orderEditReq.getState().equals("3") || orderEditReq.getState().equals("4")){
            SysOrderDelivery sysOrderDelivery = new SysOrderDelivery();
            BeanUtils.copyProperties(orderEditReq,sysOrderDelivery);
            sysOrderDelivery.setCreateAt(orderEditReq.getDeliveryAt());
            sysOrderDelivery.setState(Integer.valueOf(orderEditReq.getState()));
            sysOrderDelivery.setOid(sysOrderSupplier.getOid());
            sysOrderDelivery.setSupplierOid(sysOrderSupplier.getSupplierOid());
            log.info("sysOrderDelivery==={}",sysOrderDelivery);
            sysOrderDeliveryMapper.insert(sysOrderDelivery);
            //创建订单状态
        }
        //发送邮件
        orderMailServiceImplAsyn.sysOrderSupplierEditStateMailAsyn(JwtUtil.getCurrentUser(),orderEditReq);
        return b;
    }

    @Override
    public SupplierOrderQueryOneRes sysOrderQueryOne(BaseBeanReq req) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        SysOrderSupplier sysOrderSupplier = sysOrderSupplierMapper.selectById(req.getId());
        SupplierOrderQueryOneRes supplierOrderQueryOneRes = new SupplierOrderQueryOneRes();
        if(sysOrderSupplier!=null){
            OrderDataVO vo = new OrderDataVO();
            BeanUtils.copyProperties(sysOrderSupplier,vo);
            //查询订单留言
            QueryWrapper<SysOrderMsg> sysOrderMsgQueryWrapper=new QueryWrapper<>();
            sysOrderMsgQueryWrapper.eq("oid",sysOrderSupplier.getOid());
            List<SysOrderMsg> sysOrderMsgs = sysOrderMsgService.list(sysOrderMsgQueryWrapper);
            if(null != sysOrderMsgs && sysOrderMsgs.size()>0){
                supplierOrderQueryOneRes.setDeliveryNote(sysOrderMsgs.get(0));
            }
            //查询买家公司名称
            QueryWrapper<SysOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("oid",sysOrderSupplier.getOid());
            SysOrder one = sysOrderService.getOne(queryWrapper);
            if(null != one){
                supplierOrderQueryOneRes.setBuyerCompanyName(one.getCompanyName());
            }
            supplierOrderQueryOneRes.setSupplierOid(sysOrderSupplier.getSupplierOid());
            //查询订单详情；
            List<OrderDetailArrVO>  sysOrderDetails ;
            if(!CommonConsts.ROLE_TYPE_ADMIN.equals(currentUser.getRoleType())){
                sysOrderDetails = sysOrderDetailMapper.selectOrdertailByOidAndSupplierId(sysOrderSupplier.getOid(),currentUser.getCompanyId());
            }else {
                //管理员查询需要好到对应订单的 supplierId
                sysOrderDetails = sysOrderDetailMapper.selectOrdertailByOidAndSupplierId(sysOrderSupplier.getOid(),sysOrderSupplier.getSupplierId());
            }
            //买家公司
            SysOrder sysOrder = sysOrderService.selectOrderByOid(sysOrderSupplier.getOid());
            supplierOrderQueryOneRes.setBuyerAcc(sysOrderSupplier.getBuyerAcc());
            supplierOrderQueryOneRes.setBuyerCompanyName(sysOrder.getCompanyName());
            supplierOrderQueryOneRes.setSupplierOid(sysOrderSupplier.getSupplierOid());
            supplierOrderQueryOneRes.setSupplierCompanyName(sysOrderSupplier.getSupplierCompanyName());

            //查询相关优惠券；
            List<SysCoupon>  sysCouponList = sysCouponMapper.selectCouponByOidAndSupplierId(sysOrderSupplier.getOid(),currentUser.getCompanyId());
            vo.setOrderDetailArr(sysOrderDetails);
            vo.setUseCoupons(sysCouponList);
            supplierOrderQueryOneRes.setOrderData(vo);

            QueryWrapper<SysOrderState> w1 = new QueryWrapper<>();
            w1.eq("oid",sysOrderSupplier.getSupplierOid());
            w1.orderByAsc("state_chage_at");
            List<SysOrderState> sysOrderStates = sysOrderStateMapper.selectList(w1);
            List<OrderChangeArrVO> orderChangeArrVOS = new ArrayList<>();
            if(sysOrderStates!=null&&sysOrderStates.size()>0){
                for(SysOrderState s:sysOrderStates){
                    OrderChangeArrVO orderChangeArrVO = new OrderChangeArrVO();
                    SpringUtil.copyPropertiesIgnoreNull(s,orderChangeArrVO);
                    orderChangeArrVOS.add(orderChangeArrVO);
                }
            }
            QueryWrapper<SysOrderDelivery> w2 = new QueryWrapper<>();
            w2.eq("supplier_oid",sysOrderSupplier.getSupplierOid());
            List<SysOrderDelivery> list = sysOrderDeliveryService.list(w2);
            if(list!=null&&list.size()>0){
                supplierOrderQueryOneRes.setOrderDeliveryArr(list);
            }
            supplierOrderQueryOneRes.setSupplierCompanyName(sysOrderSupplier.getSupplierCompanyName());
            supplierOrderQueryOneRes.setOrderChangeArr(orderChangeArrVOS);
        }
        return supplierOrderQueryOneRes;
    }

    @Override
    @Transactional
    @Async
    public void createSupplierOrder(Long oid) {
        //买家已支付创建credit扣款记录
        SysOrder sysOrder = sysOrderMapper.selectOrderByOid(oid);
        //检测卖家订单是否已经被创建
        if(checkSupplierOrder(oid)){
            //已经创建；直接返回
            return;
        }
        //根据oid查询订单详情
        QueryWrapper<SysOrderDetail> w1 = new QueryWrapper<>();
        w1.eq("oid", oid);
        List<SysOrderDetail> list = sysOrderDetailService.list(w1);
        //创建卖家订单list
        List<SysOrderSupplier> sysOrderSuppliers = new ArrayList<>();
        if (list != null && list.size() > 0) {
            //根据卖家id分组
            Map<Long, List<SysOrderDetail>> collect = list.stream().collect(Collectors.groupingBy(SysOrderDetail::getSupplierId));
            //循环map
            for (Map.Entry<Long, List<SysOrderDetail>> entity : collect.entrySet()) {
                //卖家id
                Long supplierId = entity.getKey();
                //卖家的订单详情
                List<SysOrderDetail> detailList = entity.getValue();
                //判断该商家有没有订单详情
                if (detailList == null || detailList.size() < 1) {
                    continue;
                }
                SysOrderSupplier sysOrderSupplier = new SysOrderSupplier();
                //填入卖家订单基本信息
                setSupplierOrderBasic(sysOrder,supplierId,sysOrderSupplier);
                //创建卖家订单
                dealAndCreatOneSOrder(sysOrderSupplier,detailList);
                //收集处理完毕的订单
                sysOrderSuppliers.add(sysOrderSupplier);

                //发送邮件
                orderMailServiceImplAsyn.createVendorOrderMailAsyn(sysOrderSupplier,detailList);
            }
        }
        //保存卖家订单
        if (sysOrderSuppliers.size() > 0) {
            this.saveBatch(sysOrderSuppliers);
        }
    }
    private void setSupplierOrderBasic(SysOrder sysOrder, Long key, SysOrderSupplier sysOrderSupplier) {
        sysOrderSupplier.setBuyerAcc(sysOrder.getBuyerAcc());
        QueryWrapper<SysCompany> w3 = new QueryWrapper<>();
        //根据公司id查询公司信息填入卖家订单
        w3.eq("company_id", key);
        SysCompany one = sysCompanyService.getOne(w3);
        sysOrderSupplier.setSupplierCompanyName(one != null ? one.getCompanyName() : "");
        sysOrderSupplier.setSupplierCode(one != null ? one.getInviteCode() : "");
        sysOrderSupplier.setInvoiceId("IC" + sysOrder.getOid()+one.getInviteCode());
        sysOrderSupplier.setSupplierId(key);
        sysOrderSupplier.setOid(sysOrder.getOid());
        //填入卖家订单号
        sysOrderSupplier.setSupplierOid( sysOrder.getOid() + one.getInviteCode());
    }
    //各种金额
    private void dealAndCreatOneSOrder(SysOrderSupplier sysOrderSupplier, List<SysOrderDetail> detailList) {
        //获取当前税率
        BigDecimal curTax = taxService.getCurTax();
        //公有：运费
        BigDecimal deliveryFee = BigDecimal.ZERO;
        //买家相关的数据声明
        BigDecimal productFee,adaptFee,taxFee,subFee;
        productFee = BigDecimal.ZERO;
        //卖家相关的数据声明
        BigDecimal productOriFee,adaptOriFee,taxOriFee,subOriFee ;
        productOriFee = BigDecimal.ZERO;
        //发送邮件
        orderMailServiceImplAsyn.checkSupplierInverntory(detailList);
        for (SysOrderDetail s : detailList) {
            //买家查询商品的总额
            productFee = productFee.add(s.getAllmoney());
            //卖家总额
            BigDecimal basePrice = s.getOriginalSellPrice()!=null?s.getOriginalSellPrice():s.getOriginalPrice();
            productOriFee =productOriFee.add(basePrice.multiply( BigDecimal.valueOf(s.getQuantity())));
            //更改库存
            sysProductVariantSkuService.changeInventory(s.getVariantId(), s.getQuantity());
        }
        //查询商家运费
        SysCompanyLogisticsInfo logisticsInfo = sysCompanyLogisticsInfoService.findByCompanyId(sysOrderSupplier.getSupplierId());
        //无需判空；默认是0
        if (productOriFee.compareTo(logisticsInfo.getDeliveryMoq()) == -1) {
            deliveryFee = logisticsInfo.getDeliveryCharge();
        }
        //计算税
        taxFee = productFee.add(deliveryFee).multiply(curTax);
        taxOriFee = productOriFee.add(deliveryFee).multiply(curTax);

        //买家查询的订单总额 调整费用
        BigDecimal beforeSubFee = productFee.add(deliveryFee);   //卖家的商品总额无需加税；税是到公司账户；并非到买家账户
        String roundByPenny = NumberUtils.getRoundByPenny(beforeSubFee.setScale(2, BigDecimal.ROUND_HALF_DOWN));
        subFee = new BigDecimal(roundByPenny);
        adaptFee = beforeSubFee.subtract(subFee);

        //卖家查询的订单总额 调整费用
        BigDecimal beforeSubOriFee = productOriFee.add(deliveryFee); //卖家的商品总额无需加税；税是到公司账户；并非到买家账户
        String roundByPenny_ori = NumberUtils.getRoundByPenny(beforeSubOriFee.setScale(2, BigDecimal.ROUND_HALF_DOWN));
        subOriFee   =  new BigDecimal(roundByPenny_ori);
        adaptOriFee =  beforeSubOriFee.subtract(subOriFee);

        //查询使用的优惠券
        BigDecimal couponMoney = BigDecimal.ZERO;
        List<SysCouponRecord> couponRecords = sysCouponRecordMapper.selectSupplierOrderCoupon(sysOrderSupplier.getSupplierId(),sysOrderSupplier.getOid());
        if (null != couponRecords && couponRecords.size() > 0) {
            for(SysCouponRecord record:couponRecords){
                couponMoney =couponMoney.add(record.getReduceMoney());
            }
        }
        sysOrderSupplier.setCouponMoney(couponMoney);
        sysOrderSupplier.setDeliveryFee(deliveryFee);
        sysOrderSupplier.setState(0); //状态
        //买家查询的商品总额
        sysOrderSupplier.setProductFee(productFee).setAdaptFee(adaptFee).setTaxFee(taxFee).setSubFee(subFee);
        //卖家的调整费用
        sysOrderSupplier.setProductOriFee(productOriFee).setAdaptOriFee(adaptOriFee).setTaxOriFee(taxOriFee)
                .setSubOriFee(subOriFee);
        //创建记录
        sysOrderStateService.createOrderState(sysOrderSupplier.getSupplierOid(),0,sysOrderSupplier.getOid());
    }
    //检测卖家订单是否已经被创建
    private Boolean checkSupplierOrder(Long oid) {
        QueryWrapper<SysOrderSupplier> q1 = new QueryWrapper<>();
        q1.eq("oid", oid);
        List<SysOrderSupplier> list1 = this.list(q1);
        return list1.size()>0?true:false;
    }

}
